<?php

namespace App\Service;
use App\Service\CommService;
use App\Service\TaskService;
use Hyperf\DbConnection\Db;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Cache\Annotation\CachePut;
use App\Service\UserService;
use App\Service\PlayletService;
use App\Service\WxPayService;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Database\Transaction\Transaction;



class RechargeService extends CommicService
{
    private UserService $userService;
    private PlayletService $playletService;
    private TaskService $taskService;
    private WxPayService $wxPayService;


    private CommService $commService;

    public function __construct(UserService $userService,PlayletService $playletService,TaskService $taskService,CommService $commService,WxPayService $wxPayService)
    {
        $this->userService = $userService;
        $this->playletService = $playletService;
        $this->taskService = $taskService;
        $this->commService = $commService;
        $this->wxPayService = $wxPayService;
        $container = ApplicationContext::getContainer();
        $this->redis = $container->get(\Hyperf\Redis\Redis::class);
    }
    public function goods_list($applet_id,$spread_id=0,$ispay=0,$type=1){

        //2024/3/14 type等于1为普通模板，type=2为挽留模板
        if($type == 1){
            $template_info = $this->get_template($applet_id,$spread_id,$ispay);
        }else{
            $template_info = $this->get_retention_template($applet_id,$spread_id,$ispay);
        }
        if(empty($template_info)){
            return [];
        }


        $recd_data = Db::table('recharge_template_goods_rel as rec_rel')
            ->join('recharge_goods', function ($join)use ($template_info) {
                $join->on('rec_rel.recharge_goods_id', '=', 'recharge_goods.id')
                    ->where([
                        ["rec_rel.recharge_template_id","=",$template_info->id]
                    ]);
            })
//            ->select("rec_rel.recharge_goods_id","rec_rel.is_highlight","rec_rel.is_default","recharge_goods.amount","recharge_goods.name","recharge_goods.ml_coin","recharge_goods.give_coin","recharge_goods.prompt2","recharge_goods.type","recharge_goods.day")->orderBy("rec_rel.sort","desc")->get();
            ->select(
                "rec_rel.recharge_goods_id",
                "rec_rel.is_highlight",
                "rec_rel.is_default",
                "recharge_goods.amount",
                "recharge_goods.name",
                "recharge_goods.ml_coin",
                "recharge_goods.give_coin",
                "recharge_goods.prompt2",
                "recharge_goods.type",
                "recharge_goods.day",
                "recharge_goods.bgtype",
                "recharge_goods.classtext",
                "recharge_goods.classbgc",
                "recharge_goods.classcolor",
                "recharge_goods.amountcolor",
                "recharge_goods.footicon",
                "recharge_goods.foottext",
                "recharge_goods.footcolor",
                "recharge_goods.giftcolor"
            )
            ->orderBy("rec_rel.sort","desc")->get();
        $recd_data = $this->object_to_array($recd_data);
        if ($recd_data){
            $applet_info = $this->userService->get_user_applet_info($applet_id);
            foreach ($recd_data as $key =>$val){
                $recd_data[$key]["amount_name"] = number_format($val["amount"]/100,2);
//                $recd_data[$key]["amount_name"] = $val["amount"];
                $recd_data[$key]["amount"] = $val["amount"]/100;

                if ($val["give_coin"]>0){
                    $recd_data[$key]["give_coin"] =$val["give_coin"];
                    $recd_data[$key]["coin_name"] = $applet_info["coin_name"];

                    $recd_data[$key]["ml_coin"] = (string)$val["ml_coin"];
                }else{
                    if ($val["type"] == 3){
                        $recd_data[$key]["ml_coin"] = $val["name"];
                        $recd_data[$key]["give_coin"] = 0;
                        $recd_data[$key]["coin_name"] = "全场剧集免费看";

                    }else{
                        $recd_data[$key]["ml_coin"] =$val["ml_coin"].$applet_info["coin_name"];
                        $recd_data[$key]["give_coin"] = $val["give_coin"];
                        $recd_data[$key]["coin_name"] = $applet_info["coin_name"];
                    }
                }
            }
        }
        return $recd_data;
    }
    public function get_applet_id($order_id)
    {
        $res = Db::table('data_payment')->select('applet_id')->where('order_id',$order_id)->first();
        return $res;
    }
    public function get_applet(string $applet_id)
    {
        # 获取小程序基本配置
        $redis_key = "applet:config";
        $applet_info = $this->redis->hGet($redis_key,$applet_id);
        $applet_info = json_decode($applet_info,true);
        if (empty($applet_info)){
            # 获取小程序基本信息
            $applet_info = Db::table("applet")->where([
                "id"=>$applet_id
            ])->first();
            $applet_info = $this->object_to_find_array($applet_info);
            $this->redis->hSet($redis_key,$applet_id,json_encode($applet_info));
        }
        return $applet_info;
    }
    public function get_user_goods_list($applet_id,$user_id,$user_platform=1){
        echo "applet_id".$applet_id.PHP_EOL;
        echo "user_id".$user_id.PHP_EOL;
        # 判断当前用户是否充值
        $user_info = $this->userService->user_info($applet_id,$user_id);
        $data_payment = Db::table('data_payment')
            ->select('id')
            ->where('user_id',$user_id)
            ->where('applet_id',$applet_id)
            ->where('status',2)
            ->where('spread_id',$user_info->spread_id)
            ->first();
        if(!empty($data_payment)){
            $ispay = 1;
        }  else {
            $ispay = 0;
        }

        //2024/04/25 添加是否开启ios开关
        $appletData = $this->get_applet($applet_id);
        $showPay = true;
        var_dump($appletData);
        if(isset($appletData['showPay']) && $user_platform == 2){
            $showPay = $appletData['showPay'] == 1 ? true : false;
        }

        //2024/03/14 挽留充值模板
        $retention_list = $this->goods_list($applet_id,$user_info->spread_id,$ispay,2);

        $list = $this->goods_list($applet_id,$user_info->spread_id,$ispay,1);
        $rec_data = [
            "user_info"=>[
                "ml_coin"=>$user_info->ml_coin,
                "give_coin"=>$user_info->give_coin,
            ],
            "goods_list"=>$list,
            "retention_list" => $retention_list,
            "showPay" => $showPay
        ];
        return $rec_data;
    }

    public function goods_info($goods_id){
        $goods_info = Db::table("recharge_goods")->where(["id"=>$goods_id])->select("name","amount","ml_coin","give_coin","day","type")->first();
        return $goods_info;
    }

    public function get_order_id($applet_id,$user_id,$goods_id){
        $order_id = time().mt_rand(10000,99999).$applet_id.$user_id.$goods_id;
        return $order_id;
    }
    #查询微信余额
    public function check_balance($applet_id,$xc_open_id) {
        $user_info = $this->userService->get_xc_open_id_info($applet_id,$xc_open_id);
        $balance = $this->commService->query_user_balance($applet_id,$user_info);
        var_dump($balance);
        if($balance == false) {

            return 0;
        } else {
            return $balance['balance'];
        }
    }
    public function currency_pay($applet_id,$user_info,$amount,$order_id){
        $res = $this->commService->currency_pay($applet_id,$user_info,$amount,$order_id);
        var_dump('支付');
//        var_dump($res);
        if($res == false) {
            return 0;
        } else {
            return 1;
        }
    }
    public function buy_playlet($applet_id,$user_id,$playlet_id,$playlet_number){
        # 购买短剧
        $rec_data["code"]=10000;
        $user_info = $this->userService->user_info($applet_id,$user_id);
        var_dump('购买短剧');
        $playlet_number_info = $this->playletService->episodes_info($playlet_id,$playlet_number);
        if ($user_info->vip_effective_time > 0){
            $vip_effective_time = strtotime($user_info->vip_effective_time);
        }else{
            $vip_effective_time = 0 ;
        }
        if ($user_info->is_vip and $vip_effective_time>time()){
            return $rec_data;
        }else{
            $table_name = "data_user_".$applet_id;
            # 是否购买本级数
            $my_playlet_episodes = $this->playletService->get_my_playlet_episodes($applet_id,$user_id,$playlet_id);
            if (!in_array($playlet_number,$my_playlet_episodes)){
                #调用查询币的接口
//                $balance = $this->check_balance($applet_id,$user_info->xc_open_id);
                $user_m_coin = $user_info->ml_coin + $user_info->give_coin;
                $amount = $playlet_number_info["amount"];
                #查询是否推广链接的剧
                if($user_info->spread_id) {
                    $data_spread = DB::table('data_spread')->where('id',$user_info->spread_id)->first();
                    if($data_spread->playlet_id == $playlet_id) {
                        $amount = $data_spread->playlet_number_num_pay>0?$data_spread->playlet_number_num_pay:$amount;
                    }
                }

//                if ($user_m_coin >= $playlet_number_info["amount"] && $balance >=$playlet_number_info["amount"]){
                if ($user_m_coin >= $amount){
                            // 在事务中执行相关的数据库操作
                            #调用扣币接口
                            #微信扣
                            $order_id = $applet_id.$playlet_id.$playlet_number.$user_id;
                            var_dump('扣除-----');
                            $currency_pay_data['applet_id'] =$applet_id;
                            $currency_pay_data['user_info'] =$user_info;
                            $currency_pay_data['amount'] =$amount;
                            $currency_pay_data['order_id'] =$order_id;
//                            $currency_pay_data['applet_id'] =$applet_id;

//                            co(function () use ($currency_pay_data,$applet_id) {
//                                $redis_key = 'currency_pay_data:'.$applet_id;
//                                $this->redis->rPush($redis_key,json_encode($currency_pay_data));
////                                $currency = $this->currency_pay(
////                                    $currency_pay_data['applet_id'],
////                                    $currency_pay_data['user_info'],
////                                    $currency_pay_data['amount'],
////                                    $currency_pay_data['order_id']
////                                );
////                                var_dump($currency_pay_data);
//                            });
                            #内部扣
                            if ($user_info->give_coin>$amount){
                                $user_update["give_coin"] = $user_info->give_coin-$amount;
                            }else{
                                $user_update["give_coin"] = 0;
                                $y_coin = $amount - $user_info->give_coin;
                                $user_update["ml_coin"] = $user_info->ml_coin-$y_coin;
                            }
                            $add_data = [
                                "user_id"=>$user_id,
                                "applet_id"=>$applet_id,
                                "playlet_id"=>$playlet_id,
                                "playlet_number"=>$playlet_number,
                                "amount"=>$amount,
                                "order_id"=>$order_id,
                            ];
                            Db::table("data_user_pay_playlet_log")->insertGetId($add_data);
                            Db::table($table_name)->where(["id"=>$user_id])->update($user_update);
                            $this->userService->update_user_info($applet_id,$user_id);
                            $this->playletService->up_my_playlet_episodes($applet_id,$user_id,$playlet_id);
                            $this->taskService->do_task($applet_id,$user_id,3);
                            #2024-02-23 合并剧集
                            $this->playletService->set_merge_playlet_id($playlet_id,$user_id,$applet_id);

                }else{

                    $rec_data["code"] = 20061;
                }
            }
        }
        return  $rec_data;

    }
    public function get_sign($applet_id,$xc_open_id,$signDate) {
        $redis_key = 'login_info:'.$applet_id;
        $login_info = $this->redis->hGet($redis_key,$xc_open_id);
        $login_info = json_decode($login_info,true);
        $session_key = $login_info['session_key'];
        $url = "requestVirtualPayment";
        $res_data['signature'] = $this->commService->get_signature($signDate,$session_key);
        $res_data['paySig'] = $this->commService->get_paySig($applet_id,$url,$signDate);
        return $res_data;
    }
    public function buy_ios($applet_id,$user_id,$goods_id,$playlet_id){
        $buy_info = $this->buy($applet_id,$user_id,$goods_id,$playlet_id,2,2);

        $res = $this->wxPayService->unifyPay($buy_info);
        return $res;
        #小程序信息

        #
    }
    public function query_order($applet_id)
    {
        return 1;
        $table = 'data_user_'.$applet_id;
       $user =  Db::table($table)
            ->where('dyeing_time','>','2023-12-02 05:00:00')
            ->where('dyeing_time','<','2023-12-02 11:00:00')
            ->get();
       $user = $this->object_to_array($user);
       $count = count($user);
       foreach ($user as$key => $value) {
           $i = 1;

           $data_payment = Db::table('data_payment')
               ->where('order_time','>','2023-12-02 05:00:00')
               ->where('order_time','<','2023-12-02 11:00:00')
               ->where('user_id',$value['id'])
               ->first();
           $i++;
           var_dump($value['id']);
           var_dump($i.'--------'.$count);
           if($i %2000 == 0 ) {
               sleep(1);
               var_dump('暂停2秒');
           }
           if(!$data_payment) {
               continue;
           }
           co(function () use ($value,$count,$applet_id,$table) {


           $log_name = '500看币平台赠款';
           $adds_log["name"] = $log_name;
           $adds_log["amount"] = 0;
           $adds_log["give_coin"] = 500;
           $adds_log["order_id"] = 0;
           $adds_log["user_id"] = $value['id'];
           $adds_log["recharge_type"] = 0;
           $adds_log["stype"] = 1;
           $adds_log["applet_id"] = $applet_id;
           $adds_log["ml_coin"] = 0;
           Db::table("data_user_log")->insertGetId($adds_log);
           Db::table($table) ->where([
                   'id'=>$value['id']
               ])->update([
                   'give_coin'=>$value['give_coin'] +500
               ]);
           });
       }

    }


    public function buy($applet_id,$user_id,$goods_id,$playlet_id,$pay_type=1,$user_platform=1){
        # 商品信息
        $goods_info = $this->goods_info($goods_id);
        $user_info = $this->userService->user_info($applet_id,$user_id);
        #注意vip和普通不一样.vip需要支付完成后扣除所有币
        $is_vip = 0;
        if ($goods_info->type == 3){
            $is_vip = 1;
        }
        # 去第三方支付
        $add_data = [
            "user_id"=>$user_id,
            "ad_id"=>$user_info->ad_id,
            "applet_id"=>$applet_id,
            "order_id"=>$this->get_order_id($applet_id,$user_id,$goods_id),
            "merchant_id"=>$user_info->merchant_id,
            "spread_id"=>$user_info->spread_id,
            "is_vip"=>$is_vip,
            "ml_coin"=>$goods_info->ml_coin,
            "give_coin"=>$goods_info->give_coin,
            "amount"=>$goods_info->amount,
            "pay_type"=>$pay_type,
            "playlet_id"=>$playlet_id,
            "goods_id"=>$goods_id,
            "order_time"=>date("Y-m-d H:i:s"),
            "user_platform"=>$user_platform, //2024-03-14 新增用户类型1为ANDROID 2为IOS
        ];
        Db::table("data_payment")->insertGetId($add_data);
        $res_data["xc_open_id"] = $user_info->xc_open_id;
        $res_data["amount"] = $add_data["amount"];
        # 支付回掉
        $res_data['order_id'] = $add_data["order_id"];

//        $this->buyback($recdata);
        return $res_data;
    }

    public function  buyback($recdata,$type=1){
        co(function () use ($recdata,$type) {
            if($type == 1) {
                $order_id = $recdata["OutTradeNo"];
                $pay_time = $recdata['WeChatPayInfo']['PaidTime'];
                $transactionId = $recdata['WeChatPayInfo']['TransactionId'];
            }elseif($type == 4){
                $order_id = $recdata["order_id"];
                $transactionId = $recdata['wxpay_order_id'];
                $pay_time = $recdata['paid_time'];
            }else {
                $order_id = $recdata["out_trade_no"];
                $transactionId = $recdata["transaction_id"];
                $pay_time = strtotime($recdata['success_time']);
            }
            $order_info  = Db::table("data_payment")->where(["order_id"=>$order_id])->first();
            if(empty($order_info)) {
                var_dump('没有订单');
                return false;
            }
            var_dump('支付回调');
            if($order_info->status == 2) {
                var_dump('已支付');
                return false;
            }
            #ok 那就调用增加币和赠送币
            # 支付一步回掉
            $goods_info = $this->goods_info($order_info->goods_id);
            $applet_id = $order_info->applet_id;

            $user_id = $order_info->user_id;


            $user_info = $this->userService->user_info($applet_id,$user_id);

            $recharge_type = 1;
            $log_name = "充值成功";
            $currency_pay_data['applet_id'] = $applet_id;
            $currency_pay_data['user_info'] = $user_info;
            $currency_pay_data['amount'] = $order_info->amount;
            $currency_pay_data['order_id'] = $order_id;
            if ($goods_info->type == 3){
                #+vip ,先给币,后马上扣

//                co(function () use ($currency_pay_data) {
                    $currency = $this->currency_pay(
                        $currency_pay_data['applet_id'],
                        $currency_pay_data['user_info'],
                        $currency_pay_data['amount'],
                        $currency_pay_data['order_id']
                    );
                #异步扣币
                $redis_key = 'currency_pay_data:'.$applet_id;
                $this->redis->rPush($redis_key,json_encode($currency_pay_data));
//                    var_dump($currency_pay_data);
//                });
                $recharge_type  = 2;
                $log_name = "购买VIP".$goods_info->name;
                $day = $goods_info->day;
                if ($user_info->vip_effective_time > 0 &&strtotime($user_info->vip_effective_time ) > time()){
                    echo "lai".PHP_EOL;
                    $vip_effective_time = date("Y-m-d H:i:s",strtotime($user_info->vip_effective_time.'+'.$day.'days'));
                }else{
                    $vip_effective_time = date("Y-m-d H:i:s",strtotime('+'.$day.'day'));
                }
                echo "过期时间".$vip_effective_time.PHP_EOL;
                $user_update["is_vip"] = 1;
                $user_update["vip_effective_time"] = $vip_effective_time;
            }elseif($goods_info->type == 2) {
                $log_name = $goods_info->name;
                $recharge_type  = 5;
                #购买整个剧集
                $playlet_id = $order_info->playlet_id;
                if($playlet_id == 0) {
                    var_dump('没有剧集');
                    return false;
                }
                #查询所有剧集
               $playlet_episodes = Db::table("playlet_episodes")->where('playlet_id',$playlet_id)->get();
                #去掉已购买该剧集的
                $my_playlet_episodes = $this->playletService->get_my_playlet_episodes($applet_id,$user_id,$playlet_id);
                $table_name = "data_user_".$applet_id;
                foreach ($playlet_episodes as $key => $val) {
                    if (!in_array($val->playlet_number,$my_playlet_episodes)) {
//                        $order_id = $applet_id.$playlet_id.$val->playlet_number.$user_id;
                        $add_data = [
                            "user_id"=>$user_id,
                            "applet_id"=>$applet_id,
                            "playlet_id"=>$playlet_id,
                            "playlet_number"=>$val->playlet_number,
                            "amount"=>0,
                            "order_id"=>$order_id,
                        ];
                        Db::table("data_user_pay_playlet_log")->insertGetId($add_data);
                    }
                }
                $this->userService->update_user_info($applet_id,$user_id);
                $this->playletService->up_my_playlet_episodes($applet_id,$user_id,$playlet_id);
                $currency = $this->currency_pay(
                    $currency_pay_data['applet_id'],
                    $currency_pay_data['user_info'],
                    $currency_pay_data['amount'],
                    $currency_pay_data['order_id']
                );
                #2024-02-23 合并剧集
                $this->playletService->set_merge_playlet_id($playlet_id,$user_id,$applet_id);
                var_dump('整剧购买,扣币');
            }else{
                if($order_info->give_coin !=0 ) {
                    $res = $this->present_currency($applet_id,$user_info->xc_open_id,$order_id,$order_info->give_coin);
                }
                $currency = $this->currency_pay(
                    $currency_pay_data['applet_id'],
                    $currency_pay_data['user_info'],
                    $currency_pay_data['amount']+$order_info->give_coin,
                    $currency_pay_data['order_id']
                );
                #+代币
                $user_update["ml_coin"] = $user_info->ml_coin + $order_info->ml_coin;
                $user_update["give_coin"] = $user_info->give_coin + $order_info->give_coin;
            }
            $user_table = "data_user_".$order_info->applet_id;
            $adds_data = [
                "user_id"=>$order_info->user_id,
                "applet_id"=>$order_info->applet_id,
                "amount"=>$order_info->amount,
                "stype"=>1,
                "is_vip"=>$order_info->is_vip,
                "ml_coin"=>$order_info->ml_coin,
                "give_coin"=>$order_info->give_coin,
            ];

            $adds_log["name"] = $log_name;
            $adds_log["amount"] = $order_info->amount;
            $adds_log["give_coin"] = $order_info->give_coin;
            $adds_log["order_id"] = $order_id;
            $adds_log["user_id"] = $order_info->user_id;
            $adds_log["recharge_type"] = $recharge_type;
            $adds_log["stype"] = 1;
            $adds_log["applet_id"] = $order_info->applet_id;
            $adds_log["ml_coin"] = $order_info->ml_coin;
//            Db::table("data_user_recharge_log")->insertGetId($adds_data);
            Db::table("data_user_recharge_log")->insert($adds_data);

            Db::table("data_user_log")->insertGetId($adds_log);
            if(!empty($user_update)) {
                Db::table($user_table)->where([
                    "id"=>$user_id,
                ])->update($user_update);
            }
            Db::table("data_payment")
                ->where([
                    'order_id'=>$order_id
                ])
            ->update([
                'status'=>2,
//                'all_msg'=>json_encode($recdata),
                'transaction_id'=>$transactionId,
                'pay_time'=>date('Y-m-d H:i:s',$pay_time),
                'pay_remark'=>json_encode($recdata)
            ]);

            $this->userService->update_user_info($applet_id,$user_id);
            var_dump('支付成功---------------------------------');
            $hkey = 'orderback';
            $key = $order_id;
            $this->redis->hSet($hkey,$key,'ok');
            # 完成任务
//            $this->taskService->do_task($applet_id,$user_id,4);
        });

    }
    public function order_back($order_id=0) {
        if ($order_id == 0) {
            return false;
        } else {
            $hkey = 'orderback';
            $key = $order_id;
            $res = $this->redis->hGet($hkey,$key);
            if($res) {
                return true;
            } else {
                return false;
            }
        }
    }
    public function present_currency($applet_id,$xc_open_id,$order_id,$amount,$type=1) {
        $res = $this->commService->present_currency($applet_id,$xc_open_id,$order_id,$amount,$type);
        var_dump('加币');
        var_dump($res);
        return $res;
    }

}